package com.ydl.iec.transport;

import com.ydl.iec.iec104.common.BasicInstruction104;
import com.ydl.iec.iec104.core.Encoder104;
import com.ydl.iec.iec104.enums.TypeIdentifierEnum;
import com.ydl.iec.iec104.message.MessageDetail;
import com.ydl.iec.iec104.message.MessageInfo;
import com.ydl.iec.iec104.server.handler.ChannelHandler;
import com.ydl.iec.iec104.server.handler.DataHandler;
import com.ydl.iec.util.ByteUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class FileTransportHandler implements DataHandler {
    @Override
    public void handlerAdded(ChannelHandler ctx) throws Exception {
        log.info("11 连接成功");
    }

    @Override
    public void channelRead(ChannelHandler ctx, MessageDetail ruleDetail104) throws Exception {
        TypeIdentifierEnum typeIdentifierEnum = ruleDetail104.getTypeIdentifier();
        int type = typeIdentifierEnum.getValue() & 0xff;
        log.info("控制类型:{}",type);
        switch (type){
            case 0x64:
                log.info("收到总召唤");
                ctx.writeAndFlush(BasicInstruction104.getYesGeneralCallRuleDetail104());
                ctx.writeAndFlush(BasicInstruction104.getEndGeneralCallRuleDetail104());
            case 0xd2://收到文件传输请求
                director(ruleDetail104);
                break;
            case 0x2e:
                break;
            case 0x67: //时钟同步命令，忽略
                log.info("忽略时钟同步命令");
                break;
        }
    }

    private void director( MessageDetail message){
        short cos = message.getTransferReason();
        log.info("传输原因：{}",cos);
        if(cos == 0x05){//请求
            int addr = message.getMessageAddress();
            List<MessageInfo> messages = message.getMessages();
            log.info("数据地址，文件请求:{},len: {}",addr,message.getAdpuLength());
            try{
                byte[] bytes = Encoder104.encoder(message);
                log.info("收到的数据：{}", ByteUtil.byteArray2HexString(bytes,bytes.length,true));
            }catch (Exception e){
                e.printStackTrace();
            }

        }else if(cos == 0x06){//激活

        }


    }
}
